package com.foreveross.chameleon.plugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.foreveross.util.EncryptUtil;
/**
 * 加解密插件
 * @author Jianfeng.Lao
 *
 */
public class SecretPlugin extends CordovaPlugin {
	private static final String TAG="SecretPlugin";
	@Override
	public boolean execute(final String action,final CordovaArgs args, final CallbackContext callbackContext)
			throws JSONException {
		Log.v(TAG, "action>>"+action+",args>>"+args);
		cordova.getThreadPool().execute(new Runnable() {

			@Override
			public void run() {
				 try {
					JSONObject arg = args.getJSONObject(0);
					 String result = null;
					if (action != null && arg != null && !arg.isNull("algorithm") && !arg.isNull("key")) {
						try {
							if (action.equals("encode")) {
								result = EncryptUtil.encryption(arg.getString("algorithm"),
										arg.getString("key"), arg.getString("src"));
							} else if (action.equals("decode")) {
								result = EncryptUtil.decryption(arg.getString("algorithm"),
										arg.getString("key"), arg.getString("src"));
							}
							callbackContext.success(result);
						} catch (Exception e) {
							e.printStackTrace();
							callbackContext.error(e.getMessage());
						}
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});

		return true;
	}
}
